package com.tscnd.core.security; 

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.tscnd.core.service.user.IUserService;
import com.tscnd.core.utils.SysContextUtil;

public class MyAuthenticationSuccessHandler  extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler {
	
	 @Autowired
	 private IUserService userService;
	 
	 public MyAuthenticationSuccessHandler() {
	    }

		/**
		 * 构造函数设置
		 * defaulttargeturl 基类的属性。
		 * @param defaulttargeturl 用户会被重定向成功认证。
		 */
	    public MyAuthenticationSuccessHandler(String defaultTargetUrl) {
	        setDefaultTargetUrl(defaultTargetUrl);
	    }

		/**
		 * 调用父类的代码handle()方法向前或重定向到目标URL，并 然后调用
		 * clearauthenticationattributes() 删除任何剩余的会话数据。
		 */
	    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
	            Authentication authentication) throws IOException, ServletException {
	    	SysContextUtil.setRequest(request);
	    	SysContextUtil.setResponse(response);
	    	System.out.println("登录成功后发生...");
	    	try
			{
				userService.LoginSuccess();
			} catch (Exception e)
			{
				e.printStackTrace();
			}
	        handle(request, response, authentication);
	        clearAuthenticationAttributes(request);
	    }

		/**
		 * 在认证过程中  可以删除被存储在session中临时认证的相关数据
		 */
	    protected final void clearAuthenticationAttributes(HttpServletRequest request) {
	        HttpSession session = request.getSession(false);

	        if (session == null) {
	            return;
	        }

	        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
	    }

}
